import { query, logout } from '../services/app';
import { routerRedux, browserHistory } from 'dva/router';
import { message } from 'antd';
import { parse } from 'qs';
import { config, menu } from '../configs';
import { getMenu } from '../services/sysUser';
import { isSuccess } from '../configs/error';

const { prefix } = config;

export default {
	namespace: 'app',
	state: {
		user: {},
		menuPopoverVisible: false,
		siderFold: localStorage.getItem(`${prefix}siderFold`) === 'true',
		darkTheme: localStorage.getItem(`${prefix}darkTheme`) === 'true',
		isNavbar: document.body.clientWidth < 769,
		navOpenKeys: JSON.parse(localStorage.getItem(`${prefix}navOpenKeys`)) || [],
		selectedKeys: JSON.parse(localStorage.getItem(`${prefix}selectedKeys`)) || [],
		menu: [],
		settingVisible: false,
		theme: config.defaultTheme,
		showInHeader: [],
		productId: '',
		secondBread: '',
	},
	subscriptions: {

		setup({ dispatch }) {
			dispatch({ type: 'init', payload: {} });
			let tid;
			window.onresize = () => {
				clearTimeout(tid);
				tid = setTimeout(() => {
					dispatch({ type: 'changeNavbar' });
				}, 300);
			};
		},

	},
	effects: {

		*query({ payload }, { call, put }) {
			const data = yield call(query, parse(payload));
			console.log(parse)
			console.log(parse(payload))

      if (isSuccess(data)) {
				yield put({
					type: 'querySuccess',
					payload: data.data,
				});
			} else {
				yield put({ type: 'login/hideLoginLoading' });
				throw data;
			}
		},

		*logout({ payload }, { call, put }) {
			// 清除token
			window.localStorage.setItem('access_token', '');
			localStorage.setItem(`${prefix}navOpenKeys`, JSON.stringify([]));
			localStorage.setItem(`${prefix}selectedKeys`, JSON.stringify([]));
			window.location = '/login';
		},

		*changeNavbar({ payload }, { put, select }) {
			const { app } = yield (select(_ => _));
			const isNavbar = document.body.clientWidth < 769;
			if (isNavbar !== app.isNavbar) {
				yield put({ type: 'handleNavbar', payload: isNavbar });
			}
		},

		*getMenu({ payload, isLogin }, { call, put }) {
			const res = yield call(getMenu, payload);

			if (isSuccess(res)) {
				yield put({
					type: 'app/menu',
					payload: res.data
				});
				if (!isLogin) return;
				yield put({ type: 'login/hideLoginLoading' });
				if (res.data && res.data.length) {
					const home = res.data.find(m => m.router === '/deviceList') || res.data[0];

					localStorage.setItem(`${prefix}selectedKeys`, JSON.stringify([`${home.id}`])); // 默认选中首页
					yield put({
						type: 'handleSelectKeys',
						payload: { selectedKeys: [`${home.id}`] }
					});

					yield put(routerRedux.push(home.router));
				} else {
					message.warning('您当前没有任何页面权限');
				}
			}
		},

		*setting() {
			browserHistory.push('/setting');
		},

		*info() {
			// window.location = '/shareBenefitInfo';
			browserHistory.push('/shareBenefitInfo');
		},

		*init({ payload, isLogin }, { put }) {
			yield put({ type: 'query', isLogin });// 获取用户信息
			yield put({ type: 'getMenu', isLogin });// 获取用户菜单`
		}
	},
	reducers: {
		querySuccess(state, { payload: user }) {
			return {
				...state,
				user,
			};
		},

		switchSider(state) {
			localStorage.setItem(`${prefix}siderFold`, !state.siderFold);
			return {
				...state,
				siderFold: !state.siderFold,
			};
		},

		switchTheme(state) {
			localStorage.setItem(`${prefix}darkTheme`, !state.darkTheme);
			return {
				...state,
				darkTheme: !state.darkTheme,
			};
		},

		switchMenuPopver(state) {
			return {
				...state,
				menuPopoverVisible: !state.menuPopoverVisible,
			};
		},

		handleNavbar(state, { payload }) {
			return {
				...state,
				isNavbar: payload,
			};
		},

		handleNavOpenKeys(state, { payload: navOpenKeys }) {
			return {
				...state,
				...navOpenKeys,
			};
		},

		handleSelectKeys(state, { payload: selectedKeys }) {
			return {
				...state,
				...selectedKeys,
			};
		},

		menu(state, { payload }) {
			return {
				...state,
				menu: payload,
			};
		},
		// setting(state) {
		// 	return { ...state, settingVisible: !state.settingVisible };
		// },

		showInHeader(state, { showInHeader }) {
			return { ...state, showInHeader };
		},

		showSecondBread(state, { secondBread }) {
			return { ...state, secondBread };
		},

		set(state, { type, ...other }) {
			return { ...state, ...other };
		}
	},
};
